<template>
  <div class="login-page">
    <div class="login-container">
      <div class="login-card">
        <div class="login-header">
          <h1 class="login-title">{{ currentTitle }}</h1>
        </div>

        <form class="login-form" @submit.prevent="handleSubmit">
          <!-- 注册模式下的昵称字段 -->
          <div v-if="isSignupMode" class="form-group">
            <label class="form-label">昵称（可选）</label>
            <div class="input-wrapper">
              <el-icon class="input-icon">
                <User />
              </el-icon>
              <input v-model="signupForm.nickname" type="text" class="form-input" placeholder="请输入您的昵称"
                maxlength="20" />
            </div>
          </div>

          <div class="form-group">
            <label class="form-label">邮箱地址</label>
            <div class="input-wrapper">
              <el-icon class="input-icon">
                <Message />
              </el-icon>
              <input :value="isSignupMode ? signupForm.email : loginForm.email"
                @input="isSignupMode ? (signupForm.email = $event.target.value) : (loginForm.email = $event.target.value)"
                type="email" class="form-input" placeholder="请输入您的邮箱" required />
            </div>
          </div>

          <div class="form-group">
            <label class="form-label">密码</label>
            <div class="input-wrapper">
              <el-icon class="input-icon">
                <Lock />
              </el-icon>
              <input :value="isSignupMode ? signupForm.password : loginForm.password"
                @input="isSignupMode ? (signupForm.password = $event.target.value) : (loginForm.password = $event.target.value)"
                :type="showPassword ? 'text' : 'password'" class="form-input"
                :placeholder="isSignupMode ? '请输入密码（至少6位）' : '请输入您的密码'" required />
              <button type="button" class="password-toggle" @click="showPassword = !showPassword">
                <el-icon>
                  <View v-if="!showPassword" />
                  <Hide v-else />
                </el-icon>
              </button>
            </div>
          </div>

          <!-- 注册模式下的确认密码字段 -->
          <div v-if="isSignupMode" class="form-group">
            <label class="form-label">确认密码</label>
            <div class="input-wrapper">
              <el-icon class="input-icon">
                <Lock />
              </el-icon>
              <input :value="signupForm.confirmPassword" @input="signupForm.confirmPassword = $event.target.value"
                :type="showConfirmPassword ? 'text' : 'password'" class="form-input" placeholder="请再次输入密码" required />
              <button type="button" class="password-toggle" @click="showConfirmPassword = !showConfirmPassword">
                <el-icon>
                  <View v-if="!showConfirmPassword" />
                  <Hide v-else />
                </el-icon>
              </button>
            </div>
          </div>

          <!-- 登录模式下的选项 -->
          <div v-if="!isSignupMode" class="form-options">
            <label class="checkbox-wrapper">
              <input v-model="rememberMe" type="checkbox" class="checkbox" />
              <span class="checkbox-label">记住我</span>
            </label>
            <button type="button" class="forgot-password">
              忘记密码？
            </button>
          </div>

          <button type="submit" class="login-button" :disabled="loading">
            <span v-if="!loading">{{ currentButtonText }}</span>
            <div v-else class="loading-spinner">
              <el-icon class="rotating">
                <Loading />
              </el-icon>
              <span>{{ isSignupMode ? '注册中...' : '登录中...' }}</span>
            </div>
          </button>
        </form>


        <div class="signup-prompt">
          <span>{{ switchText }}</span>
          <button class="signup-link" @click="switchMode">
            {{ switchLinkText }}
          </button>
        </div>
      </div>
    </div>

    <!-- 背景装饰 -->
    <div class="background-decoration">
      <div class="decoration-circle circle-1"></div>
      <div class="decoration-circle circle-2"></div>
      <div class="decoration-circle circle-3"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Message, Lock, View, Hide, Loading, User, InfoFilled } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'

const router = useRouter()
const authStore = useAuthStore()

const loading = ref(false)
const showPassword = ref(false)
const showConfirmPassword = ref(false)
const rememberMe = ref(false)
const isSignupMode = ref(false)

const loginForm = reactive({
  email: '',
  password: ''
})

const signupForm = reactive({
  email: '',
  password: '',
  confirmPassword: '',
  nickname: ''
})

// 计算属性
const currentTitle = computed(() => isSignupMode.value ? '创建账户' : '欢迎回来')
const currentSubtitle = computed(() =>
  isSignupMode.value ? '注册您的智能首页账户' : '登录您的智能首页账户'
)
const currentButtonText = computed(() => isSignupMode.value ? '注册' : '登录')
const switchText = computed(() =>
  isSignupMode.value ? '已有账户？' : '还没有账户？'
)
const switchLinkText = computed(() => isSignupMode.value ? '立即登录' : '立即注册')

// 表单验证
const validateEmail = (email: string) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return emailRegex.test(email)
}

const validatePassword = (password: string) => {
  return password.length >= 6
}

const handleLogin = async () => {
  if (!loginForm.email || !loginForm.password) {
    ElMessage.warning('请填写完整的登录信息')
    return
  }

  if (!validateEmail(loginForm.email)) {
    ElMessage.warning('请输入有效的邮箱地址')
    return
  }

  loading.value = true

  try {
    await authStore.login(loginForm.email, loginForm.password)
    ElMessage.success('登录成功')
    router.push('/')
  } catch (error: any) {
    ElMessage.error(error.message || '登录失败')
  } finally {
    loading.value = false
  }
}

const handleSignup = async () => {
  if (!signupForm.email || !signupForm.password || !signupForm.confirmPassword) {
    ElMessage.warning('请填写完整的注册信息')
    return
  }

  if (!validateEmail(signupForm.email)) {
    ElMessage.warning('请输入有效的邮箱地址')
    return
  }

  if (!validatePassword(signupForm.password)) {
    ElMessage.warning('密码长度至少为6位')
    return
  }

  if (signupForm.password !== signupForm.confirmPassword) {
    ElMessage.warning('两次输入的密码不一致')
    return
  }

  loading.value = true

  try {
    await authStore.signup(signupForm.email, signupForm.password, {
      nickname: signupForm.nickname
    })
    ElMessage.success('注册成功，请查收邮箱验证邮件')
    // 注册成功后切换到登录模式
    isSignupMode.value = false
    // 清空表单
    Object.assign(signupForm, {
      email: '',
      password: '',
      confirmPassword: '',
      nickname: ''
    })
  } catch (error: any) {
    ElMessage.error(error.message || '注册失败')
  } finally {
    loading.value = false
  }
}

const handleSubmit = () => {
  if (isSignupMode.value) {
    handleSignup()
  } else {
    handleLogin()
  }
}

const handleSocialLogin = async (provider: string) => {
  try {
    await authStore.signInWithProvider(provider)
    ElMessage.success('登录成功')
    router.push('/')
  } catch (error: any) {
    ElMessage.error(error.message || '登录失败')
  }
}

const switchMode = () => {
  isSignupMode.value = !isSignupMode.value
  // 清空表单
  Object.assign(loginForm, { email: '', password: '' })
  Object.assign(signupForm, { email: '', password: '', confirmPassword: '', nickname: '' })
  showPassword.value = false
  showConfirmPassword.value = false
}

// 填充演示数据的方法
const fillDemoData = () => {
  if (isSignupMode.value) {
    Object.assign(signupForm, {
      email: 'demo@example.com',
      password: '123456',
      confirmPassword: '123456',
      nickname: '演示用户'
    })
  } else {
    Object.assign(loginForm, {
      email: 'demo@example.com',
      password: '123456'
    })
  }
}
</script>

<style scoped lang="scss">
.login-page {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
}

.login-container {
  width: 100%;
  max-width: 420px;
  padding: var(--spacing-lg);
  position: relative;
  z-index: 10;
}

.login-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: var(--radius-xl);
  padding: var(--spacing-2xl);
  box-shadow: var(--shadow-xl);

  [data-theme="dark"] & {
    background: rgba(15, 23, 42, 0.95);
    border: 1px solid rgba(255, 255, 255, 0.1);
  }
}

.login-header {
  text-align: center;
  margin-bottom: var(--spacing-2xl);
}

.login-title {
  font-size: var(--text-3xl);
  font-weight: 700;
  color: var(--text-primary);
  margin: 0 0 var(--spacing-sm) 0;
}

.login-subtitle {
  font-size: var(--text-base);
  color: var(--text-secondary);
  margin: 0;
}

.login-hint {
  margin-top: var(--spacing-lg);
  padding: var(--spacing-md);
  background: rgba(64, 158, 255, 0.1);
  border: 1px solid rgba(64, 158, 255, 0.2);
  border-radius: var(--radius-md);

  .hint-text {
    display: flex;
    align-items: center;
    gap: var(--spacing-xs);
    font-size: var(--text-sm);
    color: var(--primary-color);
    margin: 0 0 var(--spacing-sm) 0;

    .el-icon {
      font-size: var(--text-base);
    }
  }

  .demo-btn {
    background: transparent;
    border: 1px solid var(--primary-color);
    color: var(--primary-color);
    padding: 4px var(--spacing-sm);
    border-radius: var(--radius-sm);
    font-size: var(--text-xs);
    cursor: pointer;
    transition: all var(--transition-fast);

    &:hover {
      background: var(--primary-color);
      color: white;
    }
  }
}

.login-form {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-lg);
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-sm);
}

.form-label {
  font-size: var(--text-sm);
  font-weight: 500;
  color: var(--text-primary);
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.input-icon {
  position: absolute;
  left: var(--spacing-md);
  color: var(--text-tertiary);
  font-size: var(--text-lg);
  z-index: 1;
}

.form-input {
  width: 100%;
  padding: var(--spacing-md) var(--spacing-md) var(--spacing-md) 48px;
  border: 1px solid var(--border-color);
  border-radius: var(--radius-md);
  font-size: var(--text-base);
  color: var(--text-primary);
  background: var(--bg-primary);
  transition: all var(--transition-fast);

  &:focus {
    outline: none;
    border-color: var(--primary-color);
    box-shadow: 0 0 0 3px var(--primary-light);
  }

  &::placeholder {
    color: var(--text-placeholder);
  }
}

.password-toggle {
  position: absolute;
  right: var(--spacing-md);
  background: none;
  border: none;
  color: var(--text-tertiary);
  cursor: pointer;
  padding: 4px;
  border-radius: var(--radius-sm);
  transition: all var(--transition-fast);

  &:hover {
    color: var(--text-primary);
    background: var(--bg-secondary);
  }
}

.form-options {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.checkbox-wrapper {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
  cursor: pointer;
}

.checkbox {
  width: 16px;
  height: 16px;
  accent-color: var(--primary-color);
}

.checkbox-label {
  font-size: var(--text-sm);
  color: var(--text-secondary);
}

.forgot-password {
  background: none;
  border: none;
  color: var(--primary-color);
  font-size: var(--text-sm);
  cursor: pointer;
  text-decoration: none;

  &:hover {
    text-decoration: underline;
  }
}

.login-button {
  width: 100%;
  padding: var(--spacing-md);
  background: var(--primary-color);
  color: white;
  border: none;
  border-radius: var(--radius-md);
  font-size: var(--text-base);
  font-weight: 500;
  cursor: pointer;
  transition: all var(--transition-fast);

  &:hover:not(:disabled) {
    background: var(--primary-hover);
    transform: translateY(-1px);
    box-shadow: var(--shadow-lg);
  }

  &:disabled {
    opacity: 0.7;
    cursor: not-allowed;
    transform: none;
  }
}

.loading-spinner {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: var(--spacing-sm);
}

.rotating {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

.login-divider {
  position: relative;
  text-align: center;
  margin: var(--spacing-xl) 0;

  &::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 0;
    right: 0;
    height: 1px;
    background: var(--border-color);
  }

  span {
    background: var(--bg-primary);
    padding: 0 var(--spacing-md);
    color: var(--text-tertiary);
    font-size: var(--text-sm);
  }
}

.social-login {
  margin-bottom: var(--spacing-xl);
}

.social-button {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: var(--spacing-md);
  padding: var(--spacing-md);
  background: white;
  border: 1px solid var(--border-color);
  border-radius: var(--radius-md);
  font-size: var(--text-base);
  font-weight: 500;
  cursor: pointer;
  transition: all var(--transition-fast);

  &:hover {
    background: var(--bg-secondary);
    transform: translateY(-1px);
    box-shadow: var(--shadow-md);
  }

  [data-theme="dark"] & {
    background: var(--bg-secondary);
    color: var(--text-primary);
  }
}

.social-icon {
  width: 20px;
  height: 20px;
}

.signup-prompt {
  text-align: center;
  font-size: var(--text-sm);
  color: var(--text-secondary);
  margin-top: 1rem;
}

.signup-link {
  background: none;
  border: none;
  color: var(--primary-color);
  font-weight: 500;
  cursor: pointer;
  margin-left: var(--spacing-xs);

  &:hover {
    text-decoration: underline;
  }
}

// 背景装饰
.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: hidden;
  z-index: 1;
}

.decoration-circle {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 6s ease-in-out infinite;
}

.circle-1 {
  width: 200px;
  height: 200px;
  top: 10%;
  left: 10%;
  animation-delay: 0s;
}

.circle-2 {
  width: 150px;
  height: 150px;
  top: 60%;
  right: 10%;
  animation-delay: 2s;
}

.circle-3 {
  width: 100px;
  height: 100px;
  bottom: 20%;
  left: 20%;
  animation-delay: 4s;
}

@keyframes float {

  0%,
  100% {
    transform: translateY(0px) rotate(0deg);
  }

  50% {
    transform: translateY(-20px) rotate(180deg);
  }
}

// 响应式设计
@media (max-width: 480px) {
  .login-container {
    padding: var(--spacing-md);
  }

  .login-card {
    padding: var(--spacing-xl);
  }

  .login-title {
    font-size: var(--text-2xl);
  }
}
</style>